<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="关联客户供应商" v-bind="validateInfos.supplierName">
            <a-input v-model:value="formData.supplierName" placeholder="请输入关联客户供应商" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="卖方" v-bind="validateInfos.seller">
            <a-input v-model:value="formData.seller" placeholder="请输入卖方" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同开始时间" v-bind="validateInfos.contractStartTime">
		        <a-date-picker placeholder="请选择合同开始时间" v-model:value="formData.contractStartTime" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同结束时间" v-bind="validateInfos.contractEndTime">
		        <a-date-picker placeholder="请选择合同结束时间" v-model:value="formData.contractEndTime" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同名称" v-bind="validateInfos.contractName">
            <a-input v-model:value="formData.contractName" placeholder="请输入合同名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同编号" v-bind="validateInfos.contractId">
            <a-input v-model:value="formData.contractId" placeholder="请输入合同编号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同性质" v-bind="validateInfos.contractProperties">
	          <j-dict-select-tag v-model:value="formData.contractProperties" dictCode="" placeholder="请选择合同性质" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同类别" v-bind="validateInfos.contractType">
	          <j-dict-select-tag v-model:value="formData.contractType" dictCode="" placeholder="请选择合同类别" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="保管人" v-bind="validateInfos.managePerson">
            <a-input v-model:value="formData.managePerson" placeholder="请输入保管人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="签订时间" v-bind="validateInfos.signTime">
		        <a-date-picker placeholder="请选择签订时间"  v-model:value="formData.signTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同金额" v-bind="validateInfos.contractAmount">
	          <a-input-number v-model:value="formData.contractAmount" placeholder="请输入合同金额" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否含税" v-bind="validateInfos.istax">
            <a-input v-model:value="formData.istax" placeholder="请输入是否含税" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="税点" v-bind="validateInfos.taxPoint">
            <a-input v-model:value="formData.taxPoint" placeholder="请输入税点" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="收款人全称" v-bind="validateInfos.fullNameOfPayee">
            <a-input v-model:value="formData.fullNameOfPayee" placeholder="请输入收款人全称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="税务登记账号" v-bind="validateInfos.taxRegistrationAccountNo">
            <a-input v-model:value="formData.taxRegistrationAccountNo" placeholder="请输入税务登记账号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="收款人账号" v-bind="validateInfos.collectionAccountNo">
            <a-input v-model:value="formData.collectionAccountNo" placeholder="请输入收款人账号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="收款人开户行" v-bind="validateInfos.bankOfDeposit">
            <a-input v-model:value="formData.bankOfDeposit" placeholder="请输入收款人开户行" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="附件" v-bind="validateInfos.enclosure">
            <a-input v-model:value="formData.enclosure" placeholder="请输入附件" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane tab="采购合同明细" key="purchaseContractDetail" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="purchaseContractDetailTableRef"
          :loading="purchaseContractDetailTable.loading"
          :columns="purchaseContractDetailTable.columns"
          :dataSource="purchaseContractDetailTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="采购合同收款计划" key="purchaseContractCollectionPlan" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="purchaseContractCollectionPlanTableRef"
          :loading="purchaseContractCollectionPlanTable.loading"
          :columns="purchaseContractCollectionPlanTable.columns"
          :dataSource="purchaseContractCollectionPlanTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryPurchaseContractDetailListByMainId, queryPurchaseContractCollectionPlanListByMainId, queryDataById, saveOrUpdate } from '../PurchaseContract.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {purchaseContractDetailColumns, purchaseContractCollectionPlanColumns} from '../PurchaseContract.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "PurchaseContractForm",
    components:{
      JDictSelectTag,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const purchaseContractDetailTableRef = ref();
      const purchaseContractDetailTable = reactive<Record<string, any>>({
        loading: false,
        columns: purchaseContractDetailColumns,
        dataSource: []
      });
      const purchaseContractCollectionPlanTableRef = ref();
      const purchaseContractCollectionPlanTable = reactive<Record<string, any>>({
        loading: false,
        columns: purchaseContractCollectionPlanColumns,
        dataSource: []
      });
      const activeKey = ref('purchaseContractDetail');
      const formData = reactive<Record<string, any>>({
        id: '',
        supplierName: '',
        seller: '',
        contractStartTime: '',
        contractEndTime: '',
        contractName: '',
        contractId: '',
        contractProperties: '',
        contractType: '',
        managePerson: '',
        signTime: '',
        contractAmount: '',
        istax: '',
        taxPoint: '',
        fullNameOfPayee: '',
        taxRegistrationAccountNo: '',
        collectionAccountNo: '',
        bankOfDeposit: '',
        enclosure: '',
      });

      //表单验证
      const validatorRules = reactive({
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: true});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        purchaseContractDetailTable.dataSource = [];
        purchaseContractCollectionPlanTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const purchaseContractDetailDataList = await queryPurchaseContractDetailListByMainId(row['scid']);
        purchaseContractDetailTable.dataSource = [...purchaseContractDetailDataList];
        const purchaseContractCollectionPlanDataList = await queryPurchaseContractCollectionPlanListByMainId(row['scid']);
        purchaseContractCollectionPlanTable.dataSource = [...purchaseContractCollectionPlanDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        Object.keys(row).map(k => {
          formData[k] = row[k];
        });
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'purchaseContractDetail': purchaseContractDetailTableRef,
        'purchaseContractCollectionPlan': purchaseContractCollectionPlanTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        purchaseContractDetailTableRef,
        purchaseContractDetailTable,
        purchaseContractCollectionPlanTableRef,
        purchaseContractCollectionPlanTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>